import {Image, ScrollView, Text, View} from '@tarojs/components'
import {inject, observer} from 'mobx-react'

import './index.less'
import {observable, runInAction} from "mobx";
import BaseComponent from "../BaseComponent";
import WXUtils from "../../utils/WXUtils";
import LogService from "../../service/LogService";
import BleDeviceService from "../../service/BleDeviceService";
import DeviceConfig from "../../config/DeviceConfig";
import EventUtils from "../../utils/EventUtils";
import MessageConfig from "../../config/MessageConfig";
import BluDeviceComService from "../../service/BluDeviceComService";
import ServerConfig from "../../config/ServerConfig";
import StorageUtils from "../../utils/StorageUtils";


@inject('store')
@observer
class Index extends BaseComponent {

  @observable imgIndex = 1;
  @observable title = "当前设备无法正常连接...";
  @observable deviceState = 0;  // 0 正在扫描  1 正在连接  2连接成功  3 连接失败

  @observable devices = [];
  scanTaskNumb = undefined;
  isScan = false;
  deviceId = undefined;
  controllDisconnect = false;

  getTag() {
    return "device";
  }

  async componentDidMount() {
    super.componentDidMount();

    // super.redirectTo(`../test/device/index`);
    super.redirectTo(`../light/index`);
    return ;

    // setTimeout(() =>{
    //   super.redirectTo(`../light/index`);
    // }, 5000);

    this.scanTaskNumb = setInterval(() => {
      if (this.isScan) {
        BleDeviceService.getBluetoothDevices(DeviceConfig.DEVICE_NAME, (res) => {

          res.forEach(device => {
            let flag = 0;
            for (let i = 0; i < this.devices.length; i++) {
              if (this.devices[i].deviceId == device.deviceId) {
                flag = 1;
                break;
              }
            }
            if (flag == 0) {
              this.devices.push({...device, deviceConState: 0});
            }
          });
        })
        LogService.debug("getBluetoothDevices");
      }
    }, 50);

    EventUtils.on(MessageConfig.BlE_CONNECT_TYPE, (res) => {
      runInAction(() => {
        const {deviceId, connected} = res;
        LogService.debug("BlE_CONNECT_TYPE", res);
        if (this.deviceState != 1)
          return;

        this.devices.forEach(device => {
          if (device.deviceId == deviceId) {
            device.deviceConState = 0;
            if (connected){
              this.deviceId = deviceId;
              device.deviceConState = 2;
            }
          }
        })

        if (connected) {
          this.deviceState = 2;
        } else {
          this.deviceState = 3;
          this.devices.splice(0, this.devices.length);
        }
      })
    });

    let promise = BleDeviceService.openBlu();
    promise.then(value =>{
      this.scanDevice();
    }).catch(error =>{
      this.deviceState = 3;
      this.devices.splice(0, this.devices.length);
      LogService.error('openBlu', error);
    })
  }

  componentWillMount() {
    super.componentWillMount();
    if (!!this.scanTaskNumb) {
      clearInterval(this.scanTaskNumb);
      this.scanTaskNumb = undefined;
    }

    EventUtils.off(MessageConfig.BlE_CONNECT_TYPE);
  }

  scanDevice = async () => {
    this.controllDisconnect = true;
    await BluDeviceComService.disconnetBlue();
    let res = await BleDeviceService.scan();
    LogService.debug("scanDevice", res);
    this.controllDisconnect = false;
    if (res) {
      this.deviceState = 0;
      this.devices.splice(0, this.devices.length);
      this.isScan = true;
      setTimeout(()=>{
        if (this.deviceState == 0){
          BleDeviceService.stopSCan();
          this.isScan = false;
          this.deviceState = 3;
          this.devices.splice(0, this.devices.length);

          LogService.debug("scanDevice", "扫描超时");
        }
      }, 10000);
    } else {
      this.deviceState = 3;
      this.devices.splice(0, this.devices.length);
    }
  }

  connectDevice = (device) => {

    BleDeviceService.stopSCan();
    if (device.deviceConState != 0)
      return;

    this.isScan = false;

    this.deviceState = 1;
    device.deviceConState = 1;

    LogService.debug("connectDevice", device);
    BluDeviceComService.connetBlue(device.deviceId);
  }

  getItemView = (device) => {

    // 0 未连接  1 正在连接  2 连接成功
    let isConnect = device.deviceConState == 1;
    let text = device.deviceConState == 0 ? '未连接' : '已连接';
    return (
      <View className='device_item' onClick={() => {
        this.connectDevice(device);
      }}
      >
        <View className='device_item_img'></View>
        <View className='device_name'>{device.name}</View>
        <View className='device_item_right'>
          {!isConnect && <View className='device_connect_state'>{text}</View>}
          {isConnect && <View className='device_connect_wait'></View>}
        </View>
      </View>
    )
  }

  render() {

    // const marginTop = this.statusBarHeight;
    const tip = "1.请打开手机蓝色开关\n 2.请打开飞碟灯开关";

    let title = "";
    let imgClass = 'device_img';
    let src = `${ServerConfig.IMG_SERVER}/common/light_device.png`;

    let showTitle = true;

    switch (this.deviceState) {
      case 0:
        title = "搜索中...";
        if (this.devices.length > 0) {
          showTitle = false;
        }
        src = `${ServerConfig.IMG_SERVER}/common/light_device.gif`;
        break;
      case 1:
        // 正在连接
        break;
      case 2:
        // 连接成功
        break;
      case 3:
        title = "当前设备无法正常连接...";
        src = `http://118.31.1.101:8094/light/light_device_off.png`;
        imgClass = 'device_img.off';
        break;
    }

    return (
      <View className='device'>
        <Image className={imgClass}
               src={src}
        />
        {showTitle && <View className='device_state'>{title}</View>}
        {this.deviceState == 3 && <Text className='device_tip' onClick={this.scanDevice}>{tip}</Text>}

        {this.deviceState != 3 && this.devices.length > 0 && <ScrollView
          className='device_list'
          scrollY={true}
          scrollWithAnimation={true}
        >
          {
            this.devices.map(device => {
                return this.getItemView(device);
              }
            )
          }
        </ScrollView>
        }

        {this.deviceState == 2 && <View className='device_continue' onClick={()=>{
          if (!this.deviceId){
            StorageUtils.save('deviceId', this.deviceId);
          }
          super.redirectTo(`../light/index?deviceId=${this.deviceId}`);
        }}>继续</View>}
      </View>
    )
  }
}

export default Index
